<template>
  <div class="splice-upload-video-wrap">
    <a-upload
      v-show="canUpload"
      class="upload-dragger"
      name="file"
      :multiple="false"
      :showUploadList="false"
      :action="url"
      :disabled="isUploading"
      :customRequest="customRequest"
      :beforeUpload="beforeUpload"
      :remove="removeFile" >
      <div class="slot-upload-wrap">
        <a-button class="dg-base-btn btnItem" :loading="isUploading" >{{tips}}</a-button >
        <div class="tips">只能上传{{instance.uploadTypeMap}}, 且不超过5GB</div>
      </div>
    </a-upload>
    <div class="result-wrap">
      <div class="result-item" @mouseenter="operationIconHandle(true)" @mouseleave="operationIconHandle(false)">
        <span class="txt" @click="previewFile">{{videoResult.fileName}}</span>
        <span class="icon-list" v-show="showIcon">
          <my-icon class="my-icon" type="icon-shanchu" @click="removeFile"></my-icon>
        </span>
      </div>
      <a-progress class="progress" :stroke-color="{ from: '#7fbbff', to: '#4ca0ff' }" :percent="cutRate" :status="uploadedStatus" />
    </div>
    <VideoPlay :videoUrl="videoResult.url" ref="Modal"></VideoPlay>
  </div>
</template>

<script>
import { getStorage } from '@/utils'
import { uploadSplit } from '@/api/_utils'
import { CreateFileMd5 } from './utils'
import VideoPlay from '@/components/videoplayer/videoplayer'
const createFileMd5 = new CreateFileMd5()


export default {
  props: {
    instance: Object
  },
  data() {
    return {
      isUploading: false, // 正在上传
      url: '/file/upload',
      showIcon: false,  // icon 的显示
      uploadTotalCount: 0,  // 应该要分片的总数
      currentTime: 0, // 当前上传成功的数量
      headers: {}, // 请求头
      cutRate: 0, // 进度
      uploadedStatus: 'normal', // 进度条状态
      // 上传成功后的实例
      videoResult: {
        fileName: '',
        url: ''
      }
    }
  },
  components: {
    VideoPlay
  },
  computed: {
    canUpload() { // 但视频上传
      return this.videoResult.fileName === ''
    },
    tips() {
      return this.isUploading ? '正在上传中...' : '点击选择文件'
    }
  },
  watch: {
    instance: {
      handler(nVal) {
        if(!nVal.defaultValue) return
        this.handlerDefaultValue(nVal.defaultValue)
      },
      deep: true,
      immediate: true
    },
  },
  created() {
    this.removeFile() // 清空
    const token = `${getStorage('token', 0)}`
    this.headers = {
      Authorization: token
    }
  },
  methods: {
    // 设置默认值
    handlerDefaultValue(defaultValue) {
      const { fileName, fileUrl, url } = defaultValue
      this.videoResult = {
        fileName,
        url: fileUrl || url
      }
      this.cutRate = 100
    },
    // 自定义上传
    customRequest() {
    },
    // 校验视频
    validateVideo(file) {
      const { uploadTypeMap, maxSize } = this.instance
      if(maxSize && file.size > maxSize) {
        this.$apiStatusHandler(20, '视频资源大小不超过5GB')
        return false
      }
      const typeList = uploadTypeMap.split(',')
      const suffix = file.type.split('/')
      let isTrue = false
      suffix.forEach(key => {
        isTrue = typeList.includes(key)
      })
      if(!isTrue) {
        this.$apiStatusHandler(20, `只能上传${uploadTypeMap}`)
        return false
      }
      return true
    },
    // 上传前
    async beforeUpload(file) {
      const v = this.validateVideo(file)  // 检查
      if(!v) return false
      try {
        this.isUploading = true
        const formDataList = await createFileMd5.calMd5(file)
        this.uploadTotalCount = formDataList.length // 分片数量的总长度
        // 不上传，等待切片后上传
        this.uploadSplitContent(formDataList)
      } catch (error) {
        console.error(error.message)
        this.isUploading = false
      }
    },

    // 上传分片内容
    async uploadSplitContent(formDataList) {
      let overTime = 5  // 失败的上限次数
      let time = 1
      let result = null // 上传结果
      while(formDataList.length > 0) {
        const splitItem = formDataList.shift()  // 获取第一个
        const uploadResult = await this.invokeUploadApi(splitItem, time, overTime)
        if(uploadResult === 'stop') { // 暂停，接口报错了
          result = null
          return
        }
        result = uploadResult
        this.currentTime += 1
        this.dealRate() // 添加进度
      }
      const { code, msg, data } = result
      this.isUploading = false
      if(code !== 200) {
        this.$apiStatusHandler(code, msg)
      } else {
        const { fileId, fileName, url } = data
        this.videoResult = { fileId, fileName, url }
        this.emitVideoInfo()  // 抛出
      }
    },
    // 上传（调接口
    async invokeUploadApi(splitItem, time, overTime) {
      try {
        const result = await uploadSplit(splitItem)
        return result
      } catch (error) {
        if(time <= overTime) {
          await this.invokeUploadApi(splitItem, time++, overTime)
          return
        }
        this.$apiStatusHandler(99 ,error.message)
        this.removeFile()
        this.isUploading = false
        return 'stop'
      }
    },

    // 删除文件
    removeFile() {
      this.uploadTotalCount = 0,  // 应该要分片的总数
      this.currentTime = 0, // 当前上传成功的数量
      this.cutRate = 0, // 进度
      this.uploadedStatus = 'normal', // 进度条状态
      // 上传成功后的实例
      this.videoResult = {
        fileName: '',
        url: ''
      }
    },
    // 进度条上传进度增加处理
    dealRate() {
      const totalLen = this.uploadTotalCount  // 总共的数量
      const currentTime = this.currentTime  // 当前上传的个数
      this.cutRate = Math.floor((currentTime / totalLen) * 100)
      if (this.cutRate === 100) {  // 完成了
        this.uploadedStatus = 'success'
      }
    },
    // 视频预览
    previewFile() {
      this.$refs.Modal.showModal()
    },
    // icon 的显示
    operationIconHandle(v) {
      this.showIcon = v
    },
    // emit
    emitVideoInfo() {
      this.$emit('change', this.videoResult)
    }
  }
}
</script>
